Warning: mkdir(): No space left on device in /var/www/tg-me/post.php on line 37

Warning: file_put_contents(aCache/aDaily/post/csharp_ci/--): Failed to open stream: No such file or directory in /var/www/tg-me/post.php on line 50
C# (C Sharp) programming | Telegram Webview: csharp_ci/1371 -
Telegram Group & Telegram Channel
🧠 C# Задача: структура, интерфейс и потеря состояния

Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.

📦 Задача


using System;

public interface ICounter
{
void Increment();
int Value { get; }
}

public struct Counter : ICounter
{
private int _value;
public void Increment()
{
_value++;
}

public int Value => _value;
}

class Program
{
static void Main()
{
ICounter counter = new Counter();
counter.Increment();
counter.Increment();
Console.WriteLine(counter.Value);
}
}


Что выведет код?

A) 0

😎 1

C) 2

D) Ошибка компиляции

💡 Разбор
Наивный ответ — 2, ведь Increment() вызывается дважды. Но!

📦 Counter — это struct, то есть value type.
Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.

🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.

🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.

Ответ: 0
🧨 Подвох
Использование struct через интерфейс приводит к boxing.

Вызываемые методы действуют на копии, а не на оригинале.

Изменения теряются, и это не ошибка компиляции — это логическая ловушка.

🔧 Как исправить?
Вариант 1: Сделать Counter классом:

```csharp
public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}

public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}```


@csharp_ci



tg-me.com/csharp_ci/1371
Create:
Last Update:

🧠 C# Задача: структура, интерфейс и потеря состояния

Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.

📦 Задача


using System;

public interface ICounter
{
void Increment();
int Value { get; }
}

public struct Counter : ICounter
{
private int _value;
public void Increment()
{
_value++;
}

public int Value => _value;
}

class Program
{
static void Main()
{
ICounter counter = new Counter();
counter.Increment();
counter.Increment();
Console.WriteLine(counter.Value);
}
}


Что выведет код?

A) 0

😎 1

C) 2

D) Ошибка компиляции

💡 Разбор
Наивный ответ — 2, ведь Increment() вызывается дважды. Но!

📦 Counter — это struct, то есть value type.
Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.

🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.

🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.

Ответ: 0
🧨 Подвох
Использование struct через интерфейс приводит к boxing.

Вызываемые методы действуют на копии, а не на оригинале.

Изменения теряются, и это не ошибка компиляции — это логическая ловушка.

🔧 Как исправить?
Вариант 1: Сделать Counter классом:

```csharp
public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}

public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}```


@csharp_ci

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1371

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

For some time, Mr. Durov and a few dozen staffers had no fixed headquarters, but rather traveled the world, setting up shop in one city after another, he told the Journal in 2016. The company now has its operational base in Dubai, though it says it doesn’t keep servers there.Mr. Durov maintains a yearslong friendship from his VK days with actor and tech investor Jared Leto, with whom he shares an ascetic lifestyle that eschews meat and alcohol.

Look for Channels Online

You guessed it – the internet is your friend. A good place to start looking for Telegram channels is Reddit. This is one of the biggest sites on the internet, with millions of communities, including those from Telegram.Then, you can search one of the many dedicated websites for Telegram channel searching. One of them is telegram-group.com. This website has many categories and a really simple user interface. Another great site is telegram channels.me. It has even more channels than the previous one, and an even better user experience.These are just some of the many available websites. You can look them up online if you’re not satisfied with these two. All of these sites list only public channels. If you want to join a private channel, you’ll have to ask one of its members to invite you.

C C Sharp programming from cn


Telegram C# (C Sharp) programming
FROM USA